using B.S.BasicData.Api.Read;
using B.S.BasicData.Api.Read.Extensions;
using B.S.BasicData.Infastructure;
using B.S.BasicData.Infastructure.Implement;
using B.S.BasicData.Infastructure.Interface;
using Consul;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using NLog.Web;
using System.Reflection;
using Yitter.IdGenerator;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "B.S.BasicData.Api.Read.xml", true));
builder.Services.AddSwaggerGen(c =>
{
    //jwt鉴权在swagger中的应用
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Description = "在下框中输入请求头中需要添加Jwt授权Token：Bearer Token",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
                 {
                    Reference = new OpenApiReference
                    {
                       Type = ReferenceType.SecurityScheme,
                       Id = "Bearer"
                    }
                 },
            new string[] { }
        }
    });
});


//日志
builder.Host.UseNLog();

//服务注册
builder.Services.AddServices();//调用服务扩展方法
//builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

//EF上下文连接数据库
builder.Services.AddDbContextService<MyDbContext>(builder.Configuration.GetConnectionString("constr"),true);
//builder.Services.AddDbContext<MyDbContext>(x => x.UseSqlServer(builder.Configuration.GetConnectionString("constr")));

//JWT引用
builder.Services.AddJWT(builder);
//jwt令牌依赖注入注册
builder.Services.AddSingleton<Architecture.Common.JwtTools>();


//中介者
builder.Services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
//雪花
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
//AutoMapper
builder.Services.AddAutoMapper(typeof(MapperProfile));


#region  Consul

static void RegisterConsul()
{
    try
    {
        var consulClient = new ConsulClient(p => {
            p.Address = new Uri("http://123.56.75.137:8500");//主机ip:8500
        });
        // 2. 确保健康检查端点可访问
        var httpCheck = new AgentServiceCheck()
        {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
            Interval = TimeSpan.FromSeconds(10),
            HTTP = "http://123.56.75.137:8003/WeatherForecast", // 确认此端口服务是否运行
            Timeout = TimeSpan.FromSeconds(5)
        };
        // 3. 添加标签方便识别
        var registration = new AgentServiceRegistration()
        {
            Checks = new[] { httpCheck },
            ID = $"rbacread-{Guid.NewGuid()}", // 更易读的ID
            Name = "rbacread",                // 必须小写
            Address = "123.56.75.137",                   // 纯IP正确
            Port = 8003,                               // 端口与健康检查一致
            Tags = new[] { "dotnet-service" }           // 添加标签
        };

        // 4. 添加错误处理
        var result = consulClient.Agent.ServiceRegister(registration).Result;
        Console.WriteLine($"服务注册成功! Status: {result.StatusCode}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Consul注册失败: {ex.Message}");
    }
}


#endregion


var app = builder.Build();

RegisterConsul();


// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())//是否是开发环境
//{

//}
app.UseSwagger();
app.UseSwaggerUI();
//app.UseSwagger();
//app.UseKnife4UI();

//跨域
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());


//app.UseAuthorization();
app.UseAuthentication(); // 认证
app.UseAuthorization(); // 再授权

app.MapControllers();

app.Run();
